import d3 from "d3";
import { ElementRef } from '@angular/core';
import { CLICKTYPE, SUBTYPE } from './util';

interface Margin {
  top: number;
  right: number;
  bottom: number;
  left: number;
}

export default function (el, config) {
  d3.select('.svgG').remove()
  let currentMap;
  let g1;
  let parentEl = el.parentElement;
  let margin: Margin = { top: 20, right: 10, bottom: 10, left: 10 };
  let width: number = parentEl.clientWidth;
  let height: number = parentEl.clientHeight;
  let innerWidth: number = width - margin.left - margin.right;
  let innerHeight: number = height - margin.top - margin.bottom;
  let formatNumber = d3.format(",d");
  let transitioning: boolean;
  let colors = {
    bg: "#fff",
    navBg: "#fff", //#E8E8E8
    navColor: "#000",
    textWhite: "#fff",
    textBlack: "#000"
  }
  // 设置矩形框的填充颜色o
  let rectColor = d3.scale.pow()
    .exponent(0.6)
    .domain([-10, 0, 10])
    .range(["#009933", "#FFF", "#F33939"]);
  let x = d3.scale.linear()
    .domain([0, innerWidth])
    .range([0, innerWidth]);
  let y = d3.scale.linear()
    .domain([0, innerHeight])
    .range([0, innerHeight]);
  let treemap = d3.layout.treemap()
    .children(function (d, depth) { return depth ? null : d._children; })
    .sort(function (a, b) { return a.value - b.value; })
    .ratio(innerHeight / innerWidth * 0.5 * (1 + Math.sqrt(5)))
    .round(false);

  // set svg width&height
  let svgGP = d3.select(el)
    .attr({
      width,
      height
    })
  let svgG = svgGP.append('g')
    .attr('class', 'svgG')
  let svgGR = svgG.append("rect")
    .attr({
      class: 'bgRect',
      width,
      height,
      x: 0,
      y: 0,
      fill: colors.bg
    })
  let svg = svgG.append("g")
    .attr("transform", `translate(${margin.left}, ${margin.top})`)
    .style("shape-rendering", "crispEdges");

  let grandparent = svg.append("g")
    .attr("class", "grandparent");

  let grandparentR = grandparent.append("rect")
    .attr({
      y: -margin.top,
      width: innerWidth - 2,
      height: margin.top,
      fill: colors.navBg
    })

  grandparent.append("text")
    .attr("fill", colors.navColor)
    .attr("x", 6)
    .attr("y", 6 - margin.top)
    .attr("dy", ".75em");

  initialize(config.data);
  getSubList(config.data);
  accumulate(config.data);
  layout(config.data);
  display(config.data);

  let resizeDelayTimer = null;
  function onResize () {
    clearTimeout(resizeDelayTimer);
    resizeDelayTimer = setTimeout(function() {
      width= parentEl.clientWidth;
      height= parentEl.clientHeight;
      innerWidth= width - margin.left - margin.right;
      innerHeight= height - margin.top - margin.bottom;
      svgGP.attr({
        width,
        height
      })
      svgGR.attr({
        width,
        height
      })
      grandparentR.attr({
        width: innerWidth - 2
      })

      initialize(config.data);
      layout(config.data);

      if (currentMap && currentMap.hasOwnProperty('symbol')) {
        x.domain([currentMap.x, currentMap.x + currentMap.dx])
          .range([0, innerWidth])
        y.domain([currentMap.y, currentMap.y + currentMap.dy])
          .range([0, innerHeight])
      } else {
        x.domain([0, innerWidth])
          .range([0, innerWidth])
        y.domain([0, innerHeight])
          .range([0, innerHeight])
      }
      g1.selectAll("text").call(text);
      g1.selectAll("rect").call(rect);
    }, 100);
  }
  // 自适应
  window.addEventListener('resize', onResize, false)
  this.destroy = function () {
    window.removeEventListener('resize', onResize, false)
  }

  function initialize(root) {
    root.x = root.y = 0;
    root.dx = innerWidth;
    root.dy = innerHeight;
    root.depth = 0;
  }

  function getSubList(data) {
    console.log('%c getSubList ====>>>', 'color: #f39', data)
    let subLists = data
      ? data.children.map(d => {
        return d.symbol
      })
      : data
    // 发送需要订阅的股票
    if (!data) return
    config.clickRectEmitter.next({ type: SUBTYPE, subLists })
  }

  // function accumulate(d) {
  //   return (d._children = d.children)
  //     ? d.value = d.children.reduce(function(p, v) { return p + accumulate(v); }, 0)
  //     : d.value;
  // }
  function accumulate(d) {
    return (d._children = d.children)
      ? d.children.forEach((v) => { accumulate(v) })
      : d.value;
  }

  function layout(d) {
    if (d._children) {
      treemap.nodes({ _children: d._children });
      d._children.forEach(function (c) {
        c.x = d.x + c.x * d.dx;
        c.y = d.y + c.y * d.dy;
        c.dx *= d.dx;
        c.dy *= d.dy;
        c.parent = d;
        layout(c);
      });
    }
  }

  function display(d) {
    console.log('%c 显示的数据', 'color: #0f0', d)
    g1 = svg.insert("g", ".grandparent")
      .datum(d)
      .attr("class", "depth");

    grandparent
      .datum(d.parent)
      .attr("cursor", "pointer")
      .on("click", d => {
        currentMap = d
        getSubList(currentMap)
        transition(d, g1)
      })
      .select("text")
      .text(name(d));

    let g = g1.selectAll("g")
      .data(d._children)
      .enter().append("g");

    g.filter(function (d) { return d._children; })
      .classed("children", true)
      .attr("cursor", "pointer")

    g.append("rect")
      .attr("class", "parent")
      .attr("cursor", "pointer")
      .attr("fill", d => rectColor(d.change_rate))
      .call(rect)
      .on('click', (d) => {
        currentMap = d
        config.clickRectEmitter.next({ type: CLICKTYPE, stockInfos: d })
      })
      .append("title")
      .text(function (d) { return formatNumber(d.value); });

    g.append("text")
      .attr('class', 'symbol')
      .attr("dy", "-6px")
      .attr("text-anchor", "middle")
      .attr("dominant-baseline", "middle")
      .attr("pointer-events", "none")
      .attr("fill", d => {
        return d.change_rate < 5 && d.change_rate > -5 ? colors.textBlack : colors.textWhite
      })
      .text(function (d) { return d.name; })
      .call(text);

    g.append("text")
      .attr('class', 'change-rate')
      .attr("dy", "6px")
      .attr("text-anchor", "middle")
      .attr("dominant-baseline", "middle")
      .attr("pointer-events", "none")
      .attr("fill", d => {
        return d.change_rate < 5 && d.change_rate > -5 ? colors.textBlack : colors.textWhite
      })
      .text(function (d) { return d.change_rate + "%"; })
      .call(text);

    return g;
  }

  function transition(d, g1) {
    console.log('%c 切换动画开始 ===>>> ', 'color: #f00', d, (transitioning || !d))
    if (transitioning || !d) return;
    transitioning = true;

    let g2 = display(d);
    let t1 = g1.transition().duration(750);
    let t2 = g2.transition().duration(750);

    // Update the domain only after entering new elements.
    x.domain([d.x, d.x + d.dx]);
    y.domain([d.y, d.y + d.dy]);

    // Enable anti-aliasing during the transition.
    svg.style("shape-rendering", null);

    // Draw child nodes on top of parent nodes.
    svg.selectAll(".depth").sort(function (a, b) { return a.depth - b.depth; });

    // Fade-in entering text.
    g2.selectAll("text").style("fill-opacity", 0);

    // Transition to the new view.
    t1.selectAll("text").call(text).style("fill-opacity", 0);
    t2.selectAll("text").call(text).style("fill-opacity", 1);
    t1.selectAll("rect").call(rect);
    t2.selectAll("rect").call(rect);

    // Remove the old node when the transition is finished.
    t1.remove().each("end", function () {
      svg.style("shape-rendering", "crispEdges");
      transitioning = false;
    });
  }

  function text(text) {
    text
      .attr("x", d => {
        let w = x(d.x + d.dx) - x(d.x)
        return x(d.x) + (w / 2);
      })
      .attr("y", d => {
        let h = y(d.y + d.dy) - y(d.y)
        return y(d.y) + (h / 2);
      });
  }

  function rect(rect) {
    rect.attr("x", d => { return x(d.x); })
      .attr("y", d => { return y(d.y); })
      .attr("width", d => {
        let w = x(d.x + d.dx) - x(d.x)
        return w > 2 ? w - 2 : w
      })
      .attr("height", d => {
        let h = y(d.y + d.dy) - y(d.y)
        return h > 2 ? h - 2 : h
      });
  }

  function name(d) {
    return d.parent
      ? name(d.parent) + " > " + d.name
      : d.name;
  }

  this.update = () => {
    getSubList(currentMap)
    accumulate(currentMap)
    layout(currentMap)
    console.log('%c currentMap', 'color: #f00', currentMap)
    transition(currentMap, g1)
  }

  this.refresh = () => {
    g1.selectAll(".parent")
      .attr("fill", d => rectColor(d.change_rate))
    g1.selectAll(".change-rate")
      .attr("fill", d => {
        return d.change_rate < 5 && d.change_rate > -5 ? colors.textBlack : colors.textWhite
      })
      .text(function(d) { return d.change_rate + "%"; })
  }
}